//
//  UIColor+Ex.swift
//  App
//
//  Created by LXF on 2018/10/8.
//  Copyright © 2018年 LXF. All rights reserved.
//

import Foundation

/// UIImagePNGRepresentation
public extension Color{
    
    /// 返回 png data
    static func random(alpha:CGFloat? = nil)->Color?{
        return UIColor.init(red: XXMathLibrary.Random.randomUnitValue(), green: XXMathLibrary.Random.randomUnitValue(), blue: XXMathLibrary.Random.randomUnitValue(), alpha: alpha ?? XXMathLibrary.Random.randomUnitValue())
    }
    
    // 反色
    // importAp: 是否包含 透明通道
    func invertColor(importAp:Bool = false)->Color{
        let cs = self.colorComponents()
        return Color.init(red: 1-cs.0, green: 1-cs.1, blue: 1-cs.2, alpha: importAp ? (1-cs.3) : cs.3)
    }
    
    // 拼色
    // [percent] 调节百分比
    // [importAp] 是否包含 透明通道
    static func xx_mixing(_ color1:UIColor,_ color2:UIColor,percent:CGFloat=0.5,importAp:Bool = false)->UIColor{
        let c1 = color1.colorComponents()
        let c2 = color2.colorComponents()
        
        let r = c1.0 - (c1.0 - c2.0) * (1 - percent);
        let g = c1.1 - (c1.1 - c2.1) * (1 - percent);
        let b = c1.2 - (c1.2 - c2.2) * (1 - percent);
        
        let a = importAp ?  c1.3 - (c1.3 - c2.3) * (1 - percent)  : 1;
        
        return UIColor.init(red: r, green: g, blue: b, alpha: a)
    }
    static func xx_pickMinxColor(_ keyColors:[UIColor],_ percent:CGFloat)->UIColor?{
        let segmentCount = keyColors.count - 1
        let segment = segmentCount.toCGFloat()
        let segmentLen = 1 / segment
        
        
        for index in 0..<segmentCount{
            let minV = segmentLen * index.toCGFloat()
            let maxV = segmentLen * (index + 1).toCGFloat()
            
            if minV <= percent && maxV >= percent{
                
                let leVPer = maxV - percent
                let colorLeft = keyColors[index]
                let colorRight = keyColors[index+1]
                
                return UIColor.xx_mixing(colorLeft, colorRight, percent: leVPer)
            }
        }
        
        return nil;
    }
}


